<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use App\Model\Order;
use App\Model\OrderDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends Controller
{
    public $agent;

    public function __construct()
    {
        $this->middleware(['agent']);
        $this->agent = Auth::guard('agent')->user();
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = Order::where('agent_id', $this->agent->id);
        !empty($params['order_num']) && $model->where('order_num', $params['order_num']);
        !empty($params['mobile']) && $model->whereRaw("uid in (select id from users where username = '{$params['mobile']}')");
        isset($params['pay_status']) && $params['pay_status'] !== '' && $model->where('pay_status', $params['pay_status']);
        isset($params['status']) && $params['status'] !== '' && $model->where('status', $params['status']);
        !empty($params['start']) && $model->where('created_at', '>', $params['start']);
        !empty($params['end']) && $model->where('created_at', '<=', $params['end'] . ' 23:59:59');
        $list = $model->orderBy('id', 'desc')->paginate(15);

        return view('agent.order.index', [
            'list' => $list,
            'params' => $params,
            'statusLabels' => Order::$statusLabels,
        ]);
    }

    public function detail(Request $request)
    {
        $order = Order::with('user')->find($request->input('order_id'));
        return view('agent.order.detail', [
            'order' => $order,
            'statusLabels' => Order::$statusLabels,
            'details' => OrderDetail::where('order_id', $order['id'])->get(),
        ]);
    }

    public function saveExpressNum(Request $request)
    {
        $order_id = $request->input('order_id');
        $express_num = $request->input('express_num');
        if ($express_num) {
            Order::where('id', $order_id)->update(['express_num' => $express_num, 'status' => Order::STATUS_1]);
        }
    }

    public function finance(Request $request)
    {
        $params = $request->all();
        $start = empty($params['start']) ? date('Y-m-d') : $params['start'];
        $end = empty($params['end']) ? date('Y-m-d') : $params['end'];

        $row = Order::getFinanceInfo($this->agent->id, $start, $end);
        return view('agent.order.finance', [
            'row' => $row,
            'start' => $start,
            'end' => $end,
        ]);
    }
}